package com.haircut.security;


import com.haircut.security.model.SysUserDetails;
import com.haircut.security.model.WxAuthenticationToken;
import com.haircut.security.model.WxLoginResult;
import com.haircut.security.service.SysUserDetailsService;
import com.haircut.service.WechatUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

@Slf4j
public class WxAuthenticationProvider implements AuthenticationProvider {
    private SysUserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        WxAuthenticationToken wxAuthenticationToken = (WxAuthenticationToken) authentication;
        String mobile = wxAuthenticationToken.getMobile();
        String wxOpenid = wxAuthenticationToken.getWxOpenid();
        System.out.println("登陆手机号：" + mobile);
        System.out.println("微信openid：" + wxOpenid);

        // 如果wx_openid一致，从数据库中读取对应的用户信息
        SysUserDetails loadedUser = (SysUserDetails) userDetailsService.loadUserByWxOpenid(mobile,wxOpenid);
        if (loadedUser == null) {
            throw new UsernameNotFoundException("用户不存在");
        } else {
            WxAuthenticationToken result = new WxAuthenticationToken(loadedUser, null, loadedUser.getAuthorities());
            return result;
        }
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return WxAuthenticationToken.class.isAssignableFrom(aClass);
    }


    public void setUserDetailsService(SysUserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }
}
